package com.xincheng.shuimalong.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.MainActivity;
import com.xincheng.shuimalong.activity.address.AddressManagementActivity;
import com.xincheng.shuimalong.activity.management.ManagementActivity;
import com.xincheng.shuimalong.activity.mydetail.HistoryEarningActivity;
import com.xincheng.shuimalong.activity.mydetail.InviteActivity;
import com.xincheng.shuimalong.activity.mydetail.OrderHistoryActivity;
import com.xincheng.shuimalong.activity.mydetail.ReanNameAuthenticationActivity;
import com.xincheng.shuimalong.activity.mydetail.SettingActivity;
import com.xincheng.shuimalong.activity.mydetail.wallet.WalletActivity;
import com.xincheng.shuimalong.activity.mydetail.setting.ModifyNicknameActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.OrderConfig;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.common.UserConfig;
import com.xincheng.shuimalong.entity.user.UserHome;
import com.xincheng.shuimalong.entity.user.UserInfo;
import com.xincheng.shuimalong.manager.GlideOptionsManager;
import com.xincheng.shuimalong.util.BitmapUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Created by xuhao on 2017/6/13.
 */

public class MyselfFragment extends BaseFragment implements MainActivity.UserInfoCallBack {

    @BindView(R.id.imb_setting)
    ImageButton imbSetting;
    @BindView(R.id.img_avatar)
    ImageView imgAvatar;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_authentication)
    TextView tvAuthentication;
    @BindView(R.id.tv_reauthentication)
    TextView tvReAuthentication;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_card_issuing)
    TextView tvCardIssuing;
    @BindView(R.id.tv_total_amount)
    TextView tvTotalAmount;
    @BindView(R.id.tv_business_performance)
    TextView tvBusinessPerformance;
    @BindView(R.id.tv_comp_performance)
    TextView tvCompPerformance;
    @BindView(R.id.btn_history)
    Button btnHistory;
    @BindView(R.id.btn_my_wallet)
    Button btnMyWallet;
    @BindView(R.id.btn_management)
    Button btnManagement;
    @BindView(R.id.btn_invite)
    Button btnInvite;
    @BindView(R.id.btn_shipping_address)
    Button btnShippingAddress;
    @BindView(R.id.radio_collect_sell)
    RadioGroup radioCollectSell;
    @BindView(R.id.radio_collect)
    RadioButton radioCollect;

    @BindView(R.id.tv_num_title)
    TextView numTitleTv;
    @BindView(R.id.tv_business_performance_title)
    TextView vciTitleTv;
    @BindView(R.id.tv_comp_performance_title)
    TextView tciTitleTv;
    private File mTempFile;
    private UserHome mManagement;
    private String mUploadAvatar;
    private String mToken;
    private int mStatus = UserConfig.MONTH_RECEIPT_STATUS;
    private int mMonthNum;
    private String mReason;

    @Override
    public int getFragmentLayoutId() {
        return R.layout.fragment_my_self;
    }

    @Override
    public void initData() {
        btnManagement.setVisibility(View.GONE);
        mToken = PrefUtil.getString(getActivity(), PrefKey.TOKEN, "");
        mReason = PrefUtil.getString(getActivity(),PrefKey.LOGIN_CERT_REASON,"");
        ((MainActivity) getActivity()).registerUserInfoCallBack(this);
        collectMessage();
        mStatus = UserConfig.MONTH_RECEIPT_STATUS;
        initTitle();
    }

    private void initTitle() {
        switch (mStatus) {
            case UserConfig.MONTH_RECEIPT_STATUS:
                numTitleTv.setText(getString(R.string.receipt_month));
                vciTitleTv.setText(getString(R.string.vci_performance));
                tciTitleTv.setText(getString(R.string.tci_performance));
                break;
            case UserConfig.MONTH_SELL_STATUS:
                numTitleTv.setText(getString(R.string.sell_month));
                vciTitleTv.setText(getString(R.string.commercial_insurance_promotion_fee));
                tciTitleTv.setText(getString(R.string.compulsory_insurance_promotion_fee));
                break;
        }
    }

    public void collectMessage() {
        RetroSubscrube.getInstance().getSubscrube(
                GetParam.getAcindex(PrefUtil.getString(getContext(), PrefKey.TOKEN, "")),
                new BaseObserver(getActivity()) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            mManagement = GsonUtil.parseData(data, UserHome.class);
                            setViewMessage(mManagement);
                        }
                    }
                });
    }

    private void setViewMessage(UserHome management) {
        if (management != null) {
            mMonthNum = management.getMonthNum();
            Glide.with(getContext()).load(management.getAvatar())
                    .apply(GlideOptionsManager.getInstance().getRequestOptions()).into(imgAvatar);
            tvNickname.setText(management.getNickName() == null ? management.getUserName() :
                    management.getNickName());
            tvBalance.setText(management.getAmount() + "元");
            tvCardIssuing.setText(String.valueOf(mMonthNum));
            tvTotalAmount.setText(management.getMonthTotalMoney());
            tvBusinessPerformance.setText(management.getMonthVciMoney());
            tvCompPerformance.setText(management.getMonthTciMoney());
            mReason = management.getReason();
            initReason();
        }
    }

    private void initReason() {
        tvAuthentication.setText(mManagement.getCertMsg());
        tvAuthentication.setVisibility(View.VISIBLE);
        if (!CommonUtil.isEmpty(mReason) && mManagement.getUserCert() == 0) {
            tvReAuthentication.setVisibility(View.VISIBLE);
        }
    }

    //卖单个人中心
    private void sellMessage() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.getBillindex(mToken),
                new BaseObserver(getActivity()) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            mManagement = GsonUtil.parseData(data, UserHome.class);
                            setViewMessage(mManagement);
                        }
                    }
                });
    }

    @Override
    public void addListener() {
        radioCollectSell.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.radio_collect:
                        mStatus = UserConfig.MONTH_RECEIPT_STATUS;
                        btnManagement.setVisibility(View.GONE);
                        collectMessage();
                        initTitle();
                        break;
                    case R.id.radio_sell:
                        mStatus = UserConfig.MONTH_SELL_STATUS;
                        btnManagement.setVisibility(View.VISIBLE);
                        sellMessage();
                        initTitle();
                        break;
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.img_avatar, R.id.tv_nickname, R.id.imb_setting, R.id.tv_authentication,
            R.id.tv_reauthentication, R.id.btn_history, R.id.btn_my_wallet, R.id.btn_management,
            R.id.btn_invite, R.id.btn_shipping_address, R.id.lv_history_id})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_avatar:
                new AlertView(getActivity(), null, null, getString(R.string.cancel), null, Constant.CAMERA_OR_LOCAL,
                        AlertView.Style.ActionSheet, new OnAlertItemClickListener() {
                    @Override
                    public void onItemClick(AlertView alertView, int position) {
                        switch (position) {
                            case 0:
                                photoCamera();
                                break;
                            case 1:
                                photoLocal();
                                break;
                        }
                    }
                }).show();
                break;
            case R.id.tv_nickname:
                Bundle extras = new Bundle();
                extras.putString(IntentKey.NICK_NAME, mManagement.getNickName());
                ShowActivity.showActivityForResult(getActivity(), ModifyNicknameActivity.class, extras,
                        RequestCodeKey.GO_UPDATE_NICKNAME);
                break;
            case R.id.imb_setting://设置
                ShowActivity.showActivity(getActivity(), SettingActivity.class);
                break;
            case R.id.tv_authentication://实名认证
                if (!mManagement.isCert()) {
                    if (CommonUtil.isEmpty(mReason)) {
                        ShowActivity.showActivity(getActivity(), ReanNameAuthenticationActivity.class);
                    } else {
                        showReasonAlert(mReason);
                    }
                }
                break;
            case R.id.tv_reauthentication:
                ShowActivity.showActivity(getActivity(), ReanNameAuthenticationActivity.class);
                break;
            case R.id.btn_history://查看历史收益
                extras = new Bundle();
                extras.putInt(IntentKey.FROM, mStatus);
                extras.putString(IntentKey.ISSUING_NUMBER, String.valueOf(mManagement.getNum()));
                extras.putString(IntentKey.TOTAL_MONEY, mManagement.getTotalMoney());
                extras.putString(IntentKey.VCI_PERFORMANCE, mManagement.getTotalVciMoney());
                extras.putString(IntentKey.TCI_PERFORMANCE, mManagement.getTotalTciMoney());
                XLog.e(mManagement.toString());
                ShowActivity.showActivity(getActivity(), HistoryEarningActivity.class, extras);
                break;
            case R.id.btn_my_wallet://我的钱包
                extras = new Bundle();
                extras.putString(IntentKey.TOTAL_MONEY, mManagement.getAmount());
                switch (mStatus) {
                    case UserConfig.MONTH_RECEIPT_STATUS:
                        extras.putInt(IntentKey.ORDER_CONFIG, OrderConfig.RECEIPT);
                        break;
                    case UserConfig.MONTH_SELL_STATUS:
                        extras.putInt(IntentKey.ORDER_CONFIG, OrderConfig.SELL);
                        break;
                }

                ShowActivity.showActivityForResult(getActivity(), WalletActivity.class, extras,
                        RequestCodeKey.GO_DESPOSE);
                break;
            case R.id.btn_management://客户管理
                ShowActivity.showActivity(getActivity(), ManagementActivity.class);
                break;
            case R.id.btn_invite://邀请好友
                ShowActivity.showActivity(getActivity(), InviteActivity.class);
                break;
            case R.id.btn_shipping_address://我的收货地址
                ShowActivity.showActivity(getActivity(), AddressManagementActivity.class);
                break;
            case R.id.lv_history_id:
                if (mMonthNum == 0) {
                    return;
                }
                extras = new Bundle();
                extras.putInt(IntentKey.FROM, mStatus);
                ShowActivity.showActivity(getActivity(), OrderHistoryActivity.class, extras);
                break;
        }
    }

    private void showReasonAlert(String reason) {
        AlertView alertview = new AlertView(getActivity(), getString(R.string.hint), reason, null,
                new String[]{getString(R.string.confirm)}, null, AlertView.Style.Alert,
                new OnAlertItemClickListener() {
                    @Override
                    public void onItemClick(AlertView alertView, int position) {
                        alertView.dismiss();
                    }
                });
        alertview.show();
    }

    @Override
    public void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.TAKE_PHOTO_CAMERA:
                    if (mTempFile != null && mTempFile.exists()) {
                        mManagement.setAvatar(mTempFile.getAbsolutePath());
                    }
                    break;
                case RequestCodeKey.TAKE_PHOTO_LOCAL:
                    if (data != null && data.getData() != null) {
                        Uri uri = data.getData();
                        mManagement.setAvatar(CommonUtil.getLocalImagePath(getActivity(), uri));
                    }
                    break;
            }
            if (!CommonUtil.isEmpty(mManagement.getAvatar())) {
                Glide.with(getActivity()).load(mManagement.getAvatar()).apply(
                        GlideOptionsManager.getInstance().getRequestOptions()).into(imgAvatar);
                Glide.with(getActivity()).asBitmap().load(mManagement.getAvatar()).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                        Bitmap bitmap = resource;
                        if (resource != null && resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                            bitmap = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                        }
                        mUploadAvatar = BitmapUtil.bitmapToBase64(bitmap);
                        uploadAvator();
                    }
                });
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void uploadAvator() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.CHANGE_AVATAR, PostParam.changeAvatar(mToken, mUploadAvatar)
                , new BaseObserver(getActivity(), getString((R.string.loading_save))) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToastMsg(msg);
                    }
                });
    }

    //拍照
    private void photoCamera() {
        mTempFile = MyUtil.getOutputMediaFile(getActivity(), Constant.ID_CARD_PATH, "avatar_");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定调用相机拍照后照片的储存路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTempFile));
        startActivityForResult(intent, RequestCodeKey.TAKE_PHOTO_CAMERA);
    }

    //从相册选择
    private void photoLocal() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择一张图片"), RequestCodeKey.TAKE_PHOTO_LOCAL);
        } catch (Exception e) {
            CommonUtil.showToast(getActivity(), "请安装文件管理器");
        }
    }

    @Override
    public void changeNickName(String nickName) {
        if (!CommonUtil.isEmpty(nickName)) {
            PrefUtil.putString(getActivity(), PrefKey.LOGIN_NICKNAME, nickName);
            mManagement.setNickName(nickName);
            tvNickname.setText(mManagement.getNickName());
        }
    }

    @Override
    public void withdrawSuccess() {
        switch (mStatus) {
            case UserConfig.MONTH_RECEIPT_STATUS:
                collectMessage();
                break;
            case UserConfig.MONTH_SELL_STATUS:
                sellMessage();
                break;
        }
    }
}
